<template>
  <div>
    <el-dialog :title="title === 'add' ? '新增': (title === 'edit' ? '编辑': '复制') " :visible.sync="dialogVisible"
               :modal-append-to-body="false"
               :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="80%">
      <div v-loading="loading"
           element-loading-background="rgba(255, 255, 255, 0.6)">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row v-if="title==='edit'" class="form_row">
            <el-col>
              <el-form-item label="ID:" prop="id">
                <el-input id="id-offer-componets-creativedetail-id"
                          size="mini" disabled v-model="form.id"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="名称:" prop="name">
                <el-input id="id-offer-componets-creativedetail-name"
                          size="mini" disabled v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="form_row">
            <el-form-item label="版本" prop="version" style="width: 50%">
              <el-input id="id-offer-componets-creativedetail-version" disabled size="mini" v-model="form.version">
              </el-input>
            </el-form-item>
            <el-form-item label="需求名称" prop="version" style="width: 50%"
                          v-if="form.ownedDemandName != null && form.ownedDemandName != ''">
              <el-input id="id-offer-componets-creativedetail-ownedDemandName" disabled size="mini" v-model="form.ownedDemandName">
              </el-input>
            </el-form-item>
          </el-row>
          <el-row class="form_row">
            <el-col>
              <el-form-item label="媒体" prop="platform">
                <el-select id="id-offer-componets-creativedetail-platform" v-model="form.platform" size="mini" class="form_item" multiple>
                  <el-option v-for="(item,index) in platformsList"
                             :key="index"
                             :value="item.dictKey"
                             :label="item.dictValue" >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="设计者" prop="designer">
                <el-select id="id-offer-componets-creativedetail-designer" v-model="form.designer" size="mini" multiple filterable class="form_item">
                  <el-option v-for="(item) in originatorList"
                             v-if="(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0) || form.designer.includes(item.id)"
                             :key="item.id" :value="item.id"
                             :disabled="!(item.roleAlias.split(',').includes('designer') && item.status == 1 && item.isDeleted == 0)"
                             :label="item.realName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!--            <el-col>-->
            <!--              <el-form-item label="标签" prop="tags">-->
            <!--                <el-select v-model="form.tags" size="mini" multiple filterable-->
            <!--                           @change="creativeTags" allow-create default-first-option class="form_item">-->
            <!--                  <el-option v-for="(item,index) in tagsList" :key="index" :label="item" :value="item">-->
            <!--                  </el-option>-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
          </el-row>
          <el-row class="form_row">

            <el-col>
              <el-form-item label="原创者" prop="originator">
                <el-select id="id-offer-componets-creativedetail-originator" v-model="form.originator" filterable size="mini" multiple class="form_item">
                  <el-option v-for="(item,index) in originatorList" :key="index" :label="item.realName" :value="item.id"
                             v-if="(item.status == 1 && item.isDeleted == 0) || (title != 'add' && form.originatorOld.includes(item.id))">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="状态" prop="status">
                <el-select id="id-offer-componets-creativedetail-status" disabled v-model="form.status" size="mini" class="form_item" style="width: 44%">
                  <el-option v-for="(item,index) in statusList" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!--      只有视频才展示油管链接   -->
            <el-col :span="12">
              <el-form-item v-show="form.type===1" label="油管链接" prop="youtubeLink">
                <el-input id="id-offer-componets-creativedetail-youtubeLink" v-model="form.youtubeLink" placeholder="请输入油管链接"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="设计思路" prop="thought">
              <el-input id="id-offer-componets-creativedetail-thought" style="min-height: 100px" :autosize="{ minRows: 4}" type="textarea"
                        v-model="form.thought"></el-input>
            </el-form-item>
          </el-row>

          <el-row>
            <div style="width: 74%;margin-left:80px; margin-top: 20px;">
              <div style="margin-bottom: 10px">备注:</div>
              <el-input id="id-offer-componets-creativecheck-thought"  type="textarea" style="color: black !important;" v-model="form.remark"></el-input>
            </div>
        </el-row>



          <!--上传素材-->
          <el-row class="form_row">
            <el-form-item label="上传素材" prop="upload">
              <!--              <beetles-upload :fileList="fileList" :limit="(title === 'add' || title === 'dup')?'100':'1'" ref="beeltesUpload"></beetles-upload>-->
              <upload-obs :fileList="fileList" :limit="(title === 'add' || title === 'dup')?'100':'1'"
                          ref="beeltesUpload"></upload-obs>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button id="id-offer-componets-creativedetail-handleSubmit" :loading="loading" size="small" icon="el-icon-circle-plus-outline" type="primary"
                       style="margin-left: 60%;margin-top: 30px;"
                       @click="handleSubmit">确 定
            </el-button>
            <el-button id="id-offer-componets-creativedetail-handleClose" size="small" icon="el-icon-circle-close" @click="handleClose">取 消</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
  </div>
</template>
<script>
import {getSysDictList} from '@/api/system/dict'
import {add, getTagsList, getTenantDesigner, update} from '@/api/offer/creative'
import {getAllUser} from "@/api/user"
//import beetlesUpload from '@/components/beetles-upload/main';
import uploadObs from "@/components/beetles-upload/upload_obs";
import {mapGetters} from "vuex";
import func from '@/util/func'
import {uploadQiniuCloud} from "../../../util/qinnu_upload";

export default {
  name: 'creativeDetail',
  components: {
//    beetlesUpload,
    uploadObs,
  },
  computed: {
    ...mapGetters(["offer"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.creative_add, false),
        viewBtn: this.vaildData(this.permission.creative_view, false),
        delBtn: this.vaildData(this.permission.creative_delete, false),
        editBtn: this.vaildData(this.permission.creative_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  props: {
    dialogVisible: {
      type: String | Boolean
    },
    title: {
      type: String
    },
    dataList: {
      type: Object
    }
  },
  data() {
    return {
      loading: false,
      form: {
        id: '',
        name: '',//名称
        originator: '',//原创者
        version: '1.0',//版本号
        platform: '',//媒体
        tags: [],//标签
        designer: [],//设计者
        status: 0,//状态
        thought: '', //设计思路
        youtubeLink: '',//油管链接
        designerOld: [],
        originatorOld: [],
        remark:'',
      },
      fileList: [],//回显数据
      statusList: [
        {label: '等待提交', value: 0},
        {label: '等待审核', value: 1},
        {label: '审核通过', value: 2},
        {label: '审核拒绝', value: 3},
        {label: '禁用', value: 4}
      ],//状态列表
      tagsList: [],//标签列表
      originatorList: [],
      platformsList: [],//媒体列表
      designerList: [],//设计者列表
      rules: {
        platform: [{required: true, message: '请选择媒体', trigger: 'change'}],
        designer: [{required: true, message: '请选择设计者', trigger: 'change'}],
        // thought:[{required: true, message: '请输入设计思路', trigger: 'blur'}],
      },
    }
  },
  watch: {
    dataList: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        this.form = val
        this.form.tags = func.toList(val.tags)
        this.form.designer = func.toList(val.designer)
        this.form.originator = func.toList(val.originator)
        this.form.designerOld = [].concat(this.form.designer);
        this.form.originatorOld = [].concat(this.form.originator);
        this.form.platform = func.toList(val.platform);
        this.fileList = []
        this.fileList.push({
          name: this.form.localFilename,
          url: this.form.creativeUrl
        })
      }
    },
    dialogVisible: {
      deep: true,
      handler(val) {
        if (val) {
          getTagsList().then(res => {
            this.tagsList = res.data.data
          })
        }
      }
    },
  },
  created() {
    let self = this
    getTenantDesigner().then(res => {
      self.designerList = res.data.data
    });
    getSysDictList('platforms').then(map => {
      this.platformsList = map['platforms']
    })
    getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
      this.originatorList = res.data.data
    });
  },
  methods: {
    creativeTags(val) {
      if (val[val.length - 1].length > 10) {
        this.$message({
          type: "warning",
          message: '创建标签字数不能超过10!'
        })
        val = val.splice(val.length - 1, 1)
      }
      if (val[val.length - 1].includes(',')) {
        this.$message({
          type: "warning",
          message: '创建标签不能含有逗号!'
        })
        val.splice(val[val.length - 1])
      }

    },

    //dialog关闭
    handleClose() {
      this.fileList = []
      this.$refs.form.resetFields()
      this.$emit('close-dialog')
    },
    //提交上传
    handleSubmit() {
      let self = this;
      let files = this.verificationFiles()
      if (files === false)
        return
      if(!this.$refs.beeltesUpload.uploadCompleted()) {
        this.$message.warning('文件未上传完成');
        return;
      }
      self.$refs['form'].validate((valid) => {
        if (valid) {
          let submitForm = {
            id: self.form.id,
            name: self.form.name,
            version: self.form.version,
            // 平台
            platform: self.form.platform.join(','),
            tags: self.form.tags.join(','),
            // 设计师
            designer: self.form.designer.join(','),
            // 原创作者
            originator: self.form.originator.join(','),
            // 状态
            status: self.form.status,
            thought: self.form.thought,
            youtubeLink: self.form.youtubeLink,
            remark: self.form.remark,
            offerId: self.offer,
            filesMap: files
          }
          if (self.title === 'add') {
            self.loading = true
            self.rowSave(submitForm)
            //新增
            //参数 submitForm , files , offerId
          } else {
            //编辑
            self.loading = true
            let originId = null;
            if (self.title === 'dup') {
              submitForm.id = null;
              originId = self.form.id;
             let  creativeInfoList =new Array();
             let fileMap = this.$refs.beeltesUpload.$data.fileMap;
              fileMap.map(item => {
                creativeInfoList.push({
                  fileMap: {
                    name: item.name,
                    url: item.url,
                    type: item.type
                  },
                  though: this.dataList.though,
                  tagsSnapshot: this.dataList.tagsSnapshot,
                });
              })
              submitForm.creativeInfoList = creativeInfoList;

            }
           self.rowUpdate(submitForm, originId)
            //参数 submitForm , files ,
          }
        }
      })
    },
    rowSave(v) {
      add(v).then(res => {
        if (res.data.data) {
          this.$message.success('操作成功')
          this.loading = false
          this.handleClose()
        }
      }, error => {
        this.$message.error('操作失败')
        this.loading = false
        this.handleClose()
      })
    },
    rowUpdate(v, i) {
      v['originId'] = i
      update(v).then(res => {
        if (res.data.data) {
          this.$message.success('更新完成')
          this.loading = false
          this.handleClose()
        }
      }, error => {
        this.$message.error('更新失败')
        this.loading = false
        this.handleClose()
      })
    },

    //校验华为云素材
    verificationFiles() {
      let files = this.$refs.beeltesUpload.$data.fileMap
      if (files.length === 0) {
        this.$message({
          type: 'error',
          message: '请提供上传素材!'
        })
        return false
      }

      let complete = true // 完成度
      files.map(item => {
        if (item.progress !== 100) {
          complete = false
        }
      })

      if (!complete) {
        this.$message({
          type: 'error',
          message: '请等待素材上传完成!'
        })
        return false
      }
      let val = {}
      files.map(item => {
        val[item.name] = item.url
      })
      return val
    }
  }
}
</script>
<style lang="scss">
.form_item {
  width: 100%;
}

.form_row {
  display: flex;
}

.el-form-item_label {
  width: 80px;
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
</style>
